package com.lwx.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwx.sys.constant.Constant;
import com.lwx.sys.domain.Dept;
import com.lwx.sys.domain.User;
import com.lwx.sys.mapper.DeptMapper;
import com.lwx.sys.mapper.UserMapper;
import com.lwx.sys.service.UserService;
import com.lwx.sys.utils.DataGridView;
import com.lwx.sys.utils.FileUpLoadAndDownUtil;
import com.lwx.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwx
 * @since 2020-04-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private UserMapper userMapper;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private DeptMapper deptMapper;

    @Value("${upload.upload-root-path}")
    private String uploadRootPath;

    @Override
    public User queryUserByUserName(String username) {
        //根据用户名查询数据库
        //使用mybatis-plus
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("loginname",username);
        User user = userMapper.selectOne(userQueryWrapper);
        //相当于select * from sys_user where loginname = "system";
        return user;
    }

    @Override
    public DataGridView loadAllUser(UserVo userVo) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        qw.like(StringUtils.isNotBlank(userVo.getName()), "name", userVo.getName());
        qw.like(StringUtils.isNotBlank(userVo.getAddress()), "address", userVo.getAddress());

        qw.orderByDesc("id");
        //分页
        Page page = new Page<>(userVo.getPage(), userVo.getLimit());

        //查询数据库
        userMapper.selectPage(page, qw);
        List<User> list = page.getRecords();
        for(User user:list){
            //根据用户部门ID查部门
            Dept dept = deptMapper.selectById(user.getDeptid());
            user.setDeptname(dept.getTitle());
            //根据用户的领导ID查领导
            //判断是否有领导
            if(user.getMgr()!=null){
                User user1 = userMapper.selectById(user.getMgr());
                if (null != user1.getName()) {
                    user.setLeadername(user1.getName());
                }
            }
        }
        return new DataGridView(page.getTotal(),list);
    }

    //增删改都要加事务
    @Transactional
    @Override
    public void deleteUser(Integer id) {
//      因为有外键关联  先删除中间表
        userMapper.deleteUserPermissionByUid(id);//sys_user_permission
        userMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void batchDeleteUser(Integer[] ids) {
        Arrays.stream(ids).forEach(id ->{
            //sys_user_permission
            userMapper.deleteUserPermissionByUid(id);
        });
        userMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Transactional
    @Override
    public void addUser(User user) {
        userMapper.insert(user);
    }

    @Transactional
    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public Integer queryUserMaxOrderNum() {
        return userMapper.queryUserMaxOrderNum();
    }

    @Override
    public List<User> queryUserByDeptId(Integer deptId) {
        if (null == deptId){
            return null;
        }else {
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("type", Constant.USER_TYPE_NORMAL);
            qw.eq(true,"deptid",deptId);
            return userMapper.selectList(qw);
        }
    }

    @Override
    public User queryUserByUserId(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Transactional
    @Override
    public void saveUserRole(Integer userId,Integer[] rids) {
        //先删除后插入
        userMapper.deleteUserPermissionByUid(userId);
        if (rids != null && rids.length>0){
            for (Integer i:rids){
                //插入中间表
                userMapper.saveUserRole(userId,i);
            }
        }
    }

    @Transactional
    @Override
    public void changeUser(User user, HttpSession session) {
        //处理图片
        String imgpath = user.getImgpath();
        if (!imgpath.equals(Constant.USER_DEFAULT_IMAGE)){
            if (imgpath.endsWith("_temp")) {
                //改名
                String path = FileUpLoadAndDownUtil.changeFileName(uploadRootPath,imgpath);
                user.setImgpath(path);

                //删除原文件
                User user1 = (User) session.getAttribute("user");
                FileUpLoadAndDownUtil.deleteFile(uploadRootPath,user1.getImgpath());

            }
        }
        this.userMapper.updateById(user);

        //更新session中的user
        User user1 = this.userMapper.selectById(user.getId());
        //放入session
        session.setAttribute("userId", user1.getId());
        session.setAttribute("userName", user1.getName());
    }


}
